package com.vchecker.iobd_checker.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ConvertUtils {
    private static final Pattern REG_UNICODE = Pattern
            .compile("[0-9A-Fa-f]{4}");
    private static final Pattern EN_CODE = Pattern.compile("[A-Za-z]{4}");

    /**
     * 字符串转换成十六进制字符串
     * @author Yipb
     * @time 16-3-12 下午4:12
     * @param  str 待转换的ASCII字符串
     * @return  每个Byte之间空格分隔，如: [61 6C 6B]
     */
    public static String str2HexStr(String str)
    {

        char[] chars = "0123456789ABCDEF".toCharArray();
        StringBuilder sb = new StringBuilder("");
        byte[] bs = str.getBytes();
        int bit;

        for (int i = 0; i < bs.length; i++)
        {
            bit = (bs[i] & 0x0f0) >> 4;
            sb.append(chars[bit]);
            bit = bs[i] & 0x0f;
            sb.append(chars[bit]);
            sb.append(' ');
        }
        return sb.toString().trim();
    }

    /**
     * 十六进制转换字符串
     * @author Yipb
     * @time 16-3-12 下午4:14
     * @param hexStr Byte字符串(Byte之间无分隔符 如:[616C6B])
     * @return String 对应的字符串
     */
    public static String hexStr2Str(String hexStr)
    {
        String str = "0123456789ABCDEF";
        char[] hexs = hexStr.toCharArray();
        byte[] bytes = new byte[hexStr.length() / 2];
        int n;

        for (int i = 0; i < bytes.length; i++)
        {
            n = str.indexOf(hexs[2 * i]) * 16;
            n += str.indexOf(hexs[2 * i + 1]);
            bytes[i] = (byte) (n & 0xff);
        }
        return new String(bytes);
    }

    public static boolean isHexStr(String str) {
        boolean isHexFlg = true;

        int i = 0;
        char c;

        for (i = 0; i < str.length(); i++) {
            c = str.charAt(i);

            if ( !( ( (  c >= '0' ) && ( c <= '9' ) ) ||
                    ( (  c >= 'A' ) && ( c <= 'F' ) ) ||
                    (  c >= 'a' ) && ( c <= 'f' ) ) ) {
                isHexFlg = false;
                break;
            }
        }

        return isHexFlg;
    }


    /**
     * bytes转换成十六进制字符串
     * @param  b byte数组
     * @return 每个Byte值之间空格分隔
     */
    public static String byte2HexStr(byte[] b)
    {
        String stmp="";
        StringBuilder sb = new StringBuilder("");
        for (int n=0;n<b.length;n++)
        {
            stmp = Integer.toHexString(b[n] & 0xFF);
            sb.append((stmp.length()==1)? "0"+stmp : stmp);
            sb.append(" ");
        }
        return sb.toString().toUpperCase().trim();
    }
    /**
     * bytes转换成十六进制字符串
     * @param  b byte数组
     * @return  每个Byte值之间空格分隔
     */
    public static String byte2HexStr(byte[] b,int bLen)
    {
        String stmp="";
        StringBuilder sb = new StringBuilder("");
        for (int n=0;n<bLen;n++)
        {
            int iv = b[n] & 0xFF;
            stmp = Integer.toHexString(iv);
            sb.append((stmp.length()==1)? "0"+stmp : stmp);
            sb.append(" ");
        }
        return sb.toString().toUpperCase().trim();
    }


    /**
     * bytes字符串转换为Byte值
     * @param  src Byte字符串，每个Byte之间没有分隔符
     * @return
     */
    public static byte[] hexStr2Bytes(String src)
    {
        int m=0,n=0;
        int l=src.length()/2;
        System.out.println(l);
        byte[] ret = new byte[l];
        for (int i = 0; i < l; i++)
        {
            m=i*2+1;
            n=m+1;
            ret[i] = Byte.decode("0x" + src.substring(i*2, m) + src.substring(m,n));
        }
        return ret;
    }

    /**
     * String的字符串转换成unicode的String
     * @param  strText 全角字符串
     * @return  每个unicode之间无分隔符
     * @throws Exception
     */
    public static String strToUnicode(String strText)
            throws Exception
    {
        char c;
        StringBuilder str = new StringBuilder();
        int intAsc;
        String strHex;
        for (int i = 0; i < strText.length(); i++)
        {
            c = strText.charAt(i);
            intAsc = (int) c;
            strHex = Integer.toHexString(intAsc);
            if (intAsc > 128)
                str.append("\\u" + strHex);
            else // 低位在前面补00
                str.append("\\u00" + strHex);
        }
        return str.toString();
    }

    public static String Unicode2String(byte[] buf,int len) {
        String strValue = BytesToHexString(buf,len);
        strValue = strValue.replace(" ", "");
        return Unicode2String(strValue);
    }
    public static String Unicode2String(String str) {
        String strTemp = "";
        String sH, sL;
        for (int i = 0; i < str.length(); i += 4) {
            sL = str.substring(i, i + 2);
            sH = str.substring(i + 2, i + 4);
            if (Integer.valueOf(sH, 16) == 0 && Integer.valueOf(sL, 16) == 0)
                continue;

            if (Integer.valueOf(sH, 16) == 0) {
                strTemp += (char) Integer.parseInt(sL, 16);
            } else {
                strTemp += ("\\u");
                strTemp += sH;
                strTemp += sL;
            }
        }
        str = strTemp;

        StringBuilder sb = new StringBuilder();
        int len = str.length();
        for (int i = 0; i < len; i++) {
            char c1 = str.charAt(i);
            if (c1 == '\\' && i < len - 1) {
                char c2 = str.charAt(++i);
                if (c2 == 'u' && i <= len - 5) {
                    String tmp = str.substring(i + 1, i + 5);
                    Matcher matcher = REG_UNICODE.matcher(tmp);
                    if (matcher.find()) {
                        sb.append((char) Integer.parseInt(tmp, 16));
                        i = i + 4;
                    } else {
                        sb.append(c1).append(c2);
                    }
                } else {
                    sb.append(c1).append(c2);
                }
            } else {
                sb.append(c1);
            }
        }
        return sb.toString();
    }
    /**
     * unicode的String转换成String的字符串
     * @param  hex 16进制值字符串 （一个unicode为2byte）
     * @return  全角字符串
     */
    public static String unicodeToString(String hex)
    {
        int t = hex.length() / 6;
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < t; i++)
        {
            String s = hex.substring(i * 6, (i + 1) * 6);
            // 高位需要补上00再转
            String s1 = s.substring(2, 4) + "00";
            // 低位直接转
            String s2 = s.substring(4);
            // 将16进制的string转为int
            int n = Integer.valueOf(s1, 16) + Integer.valueOf(s2, 16);
            // 将int转换为字符
            char[] chars = Character.toChars(n);
            str.append(new String(chars));
        }
        return str.toString();
    }

    // 字节数值转十六进制字符串
    public static String BytesToHexString(byte[] bytes, int len) {
        String result = "";
        if (len > bytes.length)
            len = bytes.length;
        for (int i = 0; i < len; i++) {
            String hexString = Integer.toHexString(bytes[i] & 0xFF);
            if (hexString.length() == 1) {
                hexString = '0' + hexString;
            }
            result += hexString.toUpperCase() + " ";
        }
        return result;
    }

    //长整形转十六进制字符串
    public static String LongToHex(long lValue){
        String strValue = Long.toHexString(lValue);
        strValue = strValue.toUpperCase();
        if(strValue.length()>8)
            strValue = strValue.substring(strValue.length()-8, strValue.length());
        if(strValue.length()<8){
            int iAdd = 8-strValue.length();
            for(int i=0;i<iAdd;i++){
                strValue = "0" + strValue;
            }
        }

        return "0x" + strValue;
    }


    // 字节数值转十六进制字符串
    public static String bytes2HexString(byte[] bytes,int len) {
        String result = "";
        if(len>bytes.length)
            len = bytes.length;
        for (int i = 0; i < len; i++) {
            String hexString = Integer.toHexString(bytes[i] & 0xFF);
            if (hexString.length() == 1) {
                hexString = '0' + hexString;
            }
            result += hexString.toUpperCase() + " ";
        }
        return result;
    }

    public static int string2Int(String value){

        int retValue = 0;
        try {
            retValue = Float.valueOf(value).intValue();
        } catch (Exception e) {
            // TODO: handle exception
            return 0;
        }

        return retValue;
    }

    public static float string2Float(String value,int decLen){
        if(value.equals("")) return 0;
        float retValue = 0;
        try {
            retValue = Float.valueOf(value);
            if(decLen != 0){
                float dec = 1.0f;
                for(int i=0;i<decLen;i++)
                    dec = dec * 10.0f;

                retValue = (float) (Math.round(retValue*dec) / dec);
            }

        } catch (Exception e) {
            // TODO: handle exception
            return 0;
        }

        return retValue;
    }

    public static String double2String(double value,int decLen){
        String ret = "";
        switch (decLen) {
            case 0:
                ret = String.format("%.0f",value);
                break;
            case 1:
                ret = String.format("%.1f",value);
                break;
            case 2:
                ret = String.format("%.2f",value);
                break;
            case 3:
                ret = String.format("%.3f",value);
                break;
            case 4:
                ret = String.format("%.4f",value);
                break;
            case 5:
                ret = String.format("%.5f",value);
                break;
        }
        return ret;
    }
}
